﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.Net.Sockets;
using System.Speech.Synthesis;

namespace einuorg_console
{
    class UDPclient
    {
        private static string DatePattern = "HH:mm:ss";
        private static string GMNFIPA(string IPaddress)
        {
            string machineName = string.Empty;
            try
            {
                IPHostEntry hostEntry = Dns.GetHostEntry(IPaddress);
                machineName = hostEntry.HostName;
            }
            catch (Exception ex)
            {
                machineName = ex.ToString();
            }
            return machineName;
        }
        public static void Initialize(int port, bool voice)
        {
            SpeechSynthesizer synth = new SpeechSynthesizer();
            synth.SetOutputToDefaultAudioDevice();

            Terminal.Brackets(DateTime.Now.ToString(DatePattern), Terminal.BracketState.Success);
            Terminal.WriteLine("einuorg.UDPclient Initialized on port " + port.ToString());

            Terminal.Brackets(DateTime.Now.ToString(DatePattern), Terminal.BracketState.Info);
            Terminal.WriteLine("Waiting for broadcast...");

            bool done = false;
            UdpClient listener = new UdpClient(port);
            IPEndPoint groupEP = new IPEndPoint(IPAddress.Any, port);
            string received_data;
            byte[] receive_byte_array;
            try
            {
                while (!done)
                {
                    receive_byte_array = listener.Receive(ref groupEP);
                    Terminal.Brackets(DateTime.Now.ToString(DatePattern), Terminal.BracketState.Warning);
                    Terminal.Write(GMNFIPA(groupEP.Address.ToString()) + ": ", ConsoleColor.DarkGray);
                    received_data = Encoding.ASCII.GetString(receive_byte_array, 0, receive_byte_array.Length);
                    Terminal.WriteLine(received_data);
                    if (voice == true)
                    { 
                        synth.Speak(received_data); 
                    }
                }
            }
            catch (Exception e)
            {
                Terminal.Brackets(DateTime.Now.ToString(DatePattern), Terminal.BracketState.Error);
                Terminal.WriteLine(e.ToString());
            }
            listener.Close();
        }
    }
}
